package jp.co.cos.ittrick.channel.controller.admin;

import jp.co.cos.ittrick.channel.model.PageModel;
import jp.co.cos.ittrick.channel.model.PreModel;
import jp.co.cos.ittrick.channel.service.PageService;
import jp.co.cos.ittrick.channel.service.PreService;
import jp.co.cos.ittrick.channel.util.Utility;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;

import com.google.appengine.api.datastore.Text;

public class PreUpdateController extends Controller {

    private PreService preService;
    private PageService pageService;

    public PreUpdateController() {
        pageService = new PageService();
        preService = new PreService();
    }

    @Override
    public Navigation run() throws Exception {

        // リクエストパラメータ
        String channel = asString("channel");
        String chapter = asString("chapter");
        String page = asString("page");
        String pre = asString("pre");
        String name = asString("preName");
        String index = asString("index");
        String content = asString("content");

        PageModel pageModel = pageService.getPageByKey(Integer.valueOf(page));

        // Modelの設定
        PreModel model = preService.getPreByKey(Integer.valueOf(pre));
        if(model != null) {
            model.setName(name);
            model.setIndex(Integer.valueOf(index));
            model.getPageModelRef().setModel(pageModel);

            Utility util = new Utility();
            content = util.htmlEscape(content);
            model.setContent(new Text(content));

            // Insert
            preService.update(model);
        }

        return redirect("/admin/preEdit?channel=" + channel + "&chapter=" + chapter + "&page=" + page + "&pre=" + pre);
    }
}
